<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version
*/

namespace Dragonfly\Session\Handler;

class Database extends \Dragonfly\Session
{

	protected function setHandler()
	{
		if (!session_set_save_handler(
			array($this, 'db_open'),
			array($this, 'db_close'),
			array($this, 'db_read'),
			array($this, 'db_write'),
			array($this, 'db_destroy'),
			array($this, 'db_gc')
		))
		{
			# execution of session_set_save_handler() failed
			throw new \Exception('Could not set DB as session handler');
		}
	}

	protected function after_start($id) {}
	protected function before_write_close() {}

	#
	# Handler functions
	#

	public function db_open() { return true; }

	public function db_close() { return true; }

	public function db_read($id)
	{
		$SQL = \Dragonfly::getKernel()->SQL;
		$value = $SQL->uFetchRow("SELECT sess_reset, sess_timeout, sess_value, sess_expiry FROM {$SQL->TBL->sessions} WHERE sess_id={$SQL->quote($id)}");
		if ($value && $value[3] >= time()) {
			if ($value[0]) { $this->mode = 2; }
			$this->setTimeout($value[1]);
			return $SQL->unescapeBinary($value[2]);
		}
		return null;
	}

	public function db_destroy($id)
	{
		//$SQL = \Dragonfly::getKernel()->SQL;
		//$SQL->exec("DELETE FROM {$SQL->TBL->sessions} WHERE sess_id={$SQL->quote($id)}");
		return true;
	}

}
